using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XNgine.HelperGameComponents
{
    public class FPSCounter : DrawableGameComponent
    {
        public static SpriteFont Font { get; set; }

        public Vector2 Position { get; set; }

        private const float updateInterval = 1.0f;

        private float timeSinceLastUpdate = 0.0f;
        private float framecount = 0;

        /// <summary>
        /// The frames per second.
        /// </summary>
        public float FPS { get; private set; }

        public event EventHandler<EventArgs> Updated;

        public FPSCounter()
            : base(XEngine.Instance)
        {
            Position = new Vector2(10);
        }

        public override void Draw(GameTime gameTime)
        {
            Color color = Color.White;

            //Vector2 origin = new Vector2(0, Font.LineSpacing / 2);
            Vector2 origin = Vector2.Zero;

            XEngine.Instance.SpriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                SpriteSortMode.BackToFront, SaveStateMode.SaveState);

            XEngine.Instance.SpriteBatch.DrawString(Font, "FPS: " + FPS, Position, color, 0,
                                                     origin, Vector2.One, SpriteEffects.None, 0);

            XEngine.Instance.SpriteBatch.End();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            
            //System.Threading.Thread.Sleep(100);

            float elapsed = (float)gameTime.ElapsedRealTime.TotalSeconds;
            framecount++;
            timeSinceLastUpdate += elapsed;

            if (timeSinceLastUpdate > updateInterval)
            {
                FPS = framecount / timeSinceLastUpdate; //mean fps over updateIntrval
                framecount = 0;
                timeSinceLastUpdate -= updateInterval;

                if (Updated != null)
                    Updated(this, new EventArgs());
            }
        }

        protected override void LoadContent()
        {
            Font = XEngine.Instance.Content.Load<SpriteFont>("Fonts/menufont");
        }
    }
}